package dbadapters;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Adapter for checking if db connection exists and/or driver is accessible
 * 
 * @author gke703
 */
public class checkConnection {

	/** true if connection is good, false otherwise */
	private boolean connectionStatus;

	/** error message in the case that connection fails */
	private String errorMessage;

	/**
	 * checks if driver is in place and connection to db is possible
	 * checkConnection object will afterwards have connection status and
	 * possibly an error message as attributes
	 */
	public checkConnection() {

		boolean canConnect = true;
		String myError = "";

		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException cnfe) {
			myError = "Couldn't find driver class:";
			canConnect = false;
		}

		Connection c = null;
		try {
			c = DriverManager.getConnection(
					"jdbc:postgresql://papyrus.usask.ca/cmpt370group00",
					"cmpt370group00", "an7x482d");
			/*
			 * } catch (org.postgresql.util.PSQLException e) { canConnect=false;
			 * myError=e.toString();
			 */
		} catch (SQLException e) {
			canConnect = false;
			myError = e.toString();
		}

		if (c != null) {
			try {
				c.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		connectionStatus = canConnect;
		errorMessage = myError;

	}

	/**
	 * is connection valid or not
	 * 
	 * @return the connectionStatus
	 */
	public boolean isConnectionValid() {
		return connectionStatus;
	}

	/**
	 * @return the errorMessage, empty string if there is none
	 */
	public String getErrorMessage() {
		return errorMessage;
	}

	/**
	 * checks and prints connection status
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		checkConnection c = new checkConnection();

		System.out.println(c.isConnectionValid());
		System.out.println(c.getErrorMessage());

	}

}
